﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;

namespace Com.CodePlex.SPC3 {

    public partial class StartWorkflow : LayoutsPageBase {

        protected SPList list;
        protected SPListItem item;
        protected string workflowname;

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            list = SPContext.Current.List;
            if (list == null) {
                throw new SPException(this.GetLocString("ListPage_InvalidURL"));
            }
            string str = Request.QueryString["ItemId"];
            if (!string.IsNullOrEmpty(str)) {
                int val = 0;
                if (int.TryParse(str, out val)) {
                    try {
                        item = list.GetItemById(val);
                    } catch (Exception ex) {

                    }
                }
            }
            if (item == null) {
                Redirect();
            }
            workflowname = Request.QueryString["Workflow"];
            if (string.IsNullOrEmpty(workflowname)) {
                Redirect();
            }
            if (Literal1 != null) {
                Literal1.Text = workflowname;
                Literal2.Text = workflowname;
            }
            if (ButtonOk != null) {
                ButtonOk.Click += new EventHandler(ButtonOk_Click);
                ButtonCancel.Click += new EventHandler(ButtonCancel_Click);
            }
        }

        protected string GetLocString(string strName) {
            return (string)base.GetGlobalResourceObject("dlc", strName);
        }

        #region Button Events
        protected void ButtonOk_Click(object sender, EventArgs e) {
            SPSecurity.RunWithElevatedPrivileges(delegate() {
                using (SPSite csite = new SPSite(item.ParentList.ParentWeb.Site.ID)) {
                    using (SPWeb cweb = csite.OpenWeb(item.ParentList.ParentWeb.ID)) {
                        try {
                            cweb.AllowUnsafeUpdates = true;
                            SPList clist = cweb.Lists[item.ParentList.ID];
                            SPListItem citem = clist.GetItemById(item.ID);
                            foreach (SPWorkflow workflow in item.Workflows) {
                                if (workflow.ParentAssociation.Name == workflowname) {
                                    if (!workflow.IsCompleted) {
                                        throw new SPException("Workflow is already running.");
                                    }
                                }
                            }
                            foreach (SPWorkflowAssociation workflow in clist.WorkflowAssociations) {
                                if (workflow.Name == workflowname) {
                                    csite.WorkflowManager.StartWorkflow(citem, workflow, workflow.AssociationData);
                                    break;
                                }
                            }
                        } finally {
                            cweb.AllowUnsafeUpdates = false;
                        }
                        Redirect();
                    }
                }
            });
        }

        protected void ButtonCancel_Click(object sender, EventArgs e) {
            Redirect();
        }
        #endregion

        private void Redirect() {
            if (Request["IsDlg"] == "1") {
                Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                Context.Response.Flush();
                Context.Response.End();
            } else {
                SPUtility.Redirect(list.DefaultViewUrl, SPRedirectFlags.UseSource, Context);
            }
        }
    }
}
